# -*- coding: utf-8 -*-

import os
import socket
import time
import thread
import yaml

host = ''  
port = 6633

log = open('server.log', 'a+')

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)

def get_version(program):
	return str(config[program]['version'])
	
def get_desc(program):
	return str(config[program]['description'])
	
def get_list(program):
	result = ''
	for s in config[program]['files']:
		result = result + s + '\r\n'
	return result	

def get_size(program, file):
	if config[program]['files'].has_key(file):
		return str(os.path.getsize(config[program]['files'][file]['path'] + file))
	else:
		return '0'
	
def get_file(program, file):
	file = config[program]['files'][file]['path'] + file
	size = os.path.getsize(file)
	f = open(file, 'rb')
	buf = f.read(size)
	f.close()
	
	return buf

def get_action(program, file):
	return config[program]['files'][file]['action']

def write_log(ip, cmd, program, file):
	log.write('%s\t%s\t%s\t%s\t%s\r\n' % (time.strftime('%d.%m.%Y %H:%M:%S', time.gmtime()), ip, cmd.upper(), program, file))
	log.flush()	
	
def client_thread(socket, addr):
	while 1:
		data = socket.recv(1024)
		if not data: break
	
		data = data.split(' ')
		cmd = data[0].strip().lower()
		program = data[1].strip().lower()
		file = ''
	
		if len(data) == 3: 
			file = data[2].strip().lower()

		write_log(addr[0], cmd, program, file)
	
		if cmd == 'version':
			socket.send(get_version(program))

		if cmd == 'desc':
			socket.send(get_desc(program))

		if cmd == 'list':
			socket.send(get_list(program))	

		if cmd == 'size':
			socket.send(get_size(program, file))

		if cmd == 'get':			
			socket.send(get_file(program, file))

		if cmd == 'action':
			socket.send(get_action(program, file))
	
	socket.close()	
			
print 'server started'
		
while 1:	
	conn, addr = s.accept()

	f = open('config.yaml', 'r')
	config = yaml.load(f)
	f.close()

	thread.start_new_thread(client_thread, (conn, addr))

log.close()
s.close()
